<template>
  <ex-dialog width="50%" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading" style="position: relative;">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本设置" name="first">
          <el-form :model="ruleForm" ref="ruleForm" class="demo-ruleForm" :disabled="lookStatus">
            <el-form-item label="通知标题" :label-width="labelWidth" required>
              <el-input v-model="ruleForm.title" placeholder="请输入" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="通知副标题" :label-width="labelWidth" required>
              <el-input v-model="ruleForm.details" placeholder="请输入" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="通知内容" :label-width="labelWidth"></el-form-item>
          </el-form>
          <div class="richText">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 400px; overflow-y: hidden;" v-model="ruleForm.content" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="通知人数" name="second">
          <el-form :label-width="labelWidth">
            <el-form-item label="通知用户：" prop="" v-if="!lookStatus">
              <el-upload class="upload-demo" :action="fileaction" :headers="headers" :limit="1"
                :on-success="handleFileChange" :on-error="handleFileError" :show-file-list="true" :file-list="fileList">
                <el-button type="primary" size="small">导入用户</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
            <el-form-item label="附赠权益：">
              <el-switch v-model="ruleForm.useEquity" active-value="1" inactive-value="0" active-text="是否启用附赠权益"
                :disabled="lookStatus"> </el-switch>
              <!-- <el-select v-model="ruleForm.equityInventoryId" placeholder="选择权益" clearable
                style="width: 230px;margin-left: 20px;" :disabled="lookStatus" v-if="ruleForm.useEquity == 1">
                <el-option v-for="item in equityInventoryList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select> -->
            </el-form-item>
            <el-form-item label="" v-if="ruleForm.useEquity == 1">
              <el-radio-group v-model="ruleForm.equityType" @change="changeEquityType">
                <el-radio :label="'1'">
                  <span>权益库存</span>
                  <el-select v-model="ruleForm.equityInventoryId" placeholder="选择权益" clearable
                    style="width: 230px;margin-left: 20px;" :disabled="lookStatus" v-if="ruleForm.equityType == '1'" filterable>
                    <el-option v-for="item in equityInventoryList" :key="item.id" :label="item.value" :value="item.id" />
                  </el-select>
                </el-radio>
                <el-radio :label="'2'">
                  <span>统一链接</span>
                  <el-input v-model="ruleForm.unifyUrl" placeholder="请输入" style="width:230px;margin-left:10px"
                    v-if="ruleForm.equityType == '2'"></el-input>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户手机号：" prop="" v-if="!lookStatus">
              <el-input v-model="customerformPhone" placeholder="请输入用户手机号" style="width: 200px;" />
              <el-button type="primary" size="small" style="margin-left: 20px" @click="addUser" :loading="addLoading">添加
              </el-button>
              <el-button type="primary" size="small" style="margin-left: 20px" @click="wipeData" :loading="addLoading">
                清空导入数据</el-button>
            </el-form-item>
          </el-form>
          <div class="tabel_box">
            <el-table :data="ruleForm.customerList" v-loading="loading" element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.6)" element-loading-text="加载中" stripe border max-height="500">
              <el-table-column label="序号" align="center" type="index" width="64px" />
              <el-table-column label="用户姓名" align="center" prop="name" :show-overflow-tooltip="true" />
              <el-table-column label="手机号" align="center" prop="phone" :show-overflow-tooltip="true" />
              <el-table-column label="获赠权益数量" align="center" prop="time" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <div v-if="noticetype == 'look'">
                    <span>{{scope.row.codeTotal}}</span>
                  </div>
                  <div v-else>
                    <el-input type="number" v-model="ruleForm.customerList[scope.$index].codeTotal"
                      @input="(e) => (ruleForm.customerList[scope.$index].codeTotal = integerFn(e))" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!lookStatus">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="deleteView(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- <el-form :label-width="labelWidth" :inline="true" >
            <el-form-item label="附赠权益："  label-width='150px'>
                <el-switch v-model="ruleForm.useEquity" active-value="1" inactive-value="0" active-text="是否启用附赠权益" :disabled="lookStatus"> </el-switch>
            </el-form-item>
            <el-form-item style="margin-left: 20px;" v-if="ruleForm.useEquity == 1">
                <el-select  v-model="ruleForm.equityInventoryId" placeholder="选择权益" clearable style="width: 230px;" :disabled="lookStatus">
                  <el-option v-for="item in equityInventoryList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
         </el-form> -->
          <!-- 导入失败弹窗 -->
          <el-dialog title="导入失败" :visible.sync="dialogVisible" width="500" append-to-body>
            <div>{{importMessage}}</div>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="button_box">
      <el-button type="primary" :loading="AgreeLoading" @click="submitForm(1)" v-if="noticetype != 'look'">保存草稿
      </el-button>
      <el-button type="primary" :loading="AgreeLoading" @click="submitForm(2)" v-if="noticetype != 'look'">发送通知
      </el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
  import {
    getToken
  } from "@/utils/auth";
  import Loading from "@/components/Loading/index";
  // import Editor from '@/components/Editor';
  import '@wangeditor/editor/dist/css/style.css'
  import {
    Editor,
    Toolbar
  } from "@wangeditor/editor-for-vue";
  // api
  import {
    getMessageId,
    getCustomerPhone,
    addCustomerMessage,
    editCustomerMessage,
    inventorySelectList,
    currentInventorySelect
  } from "@/api/sYMessageNotification";

  export default {
    components: {
      Loading,
      // Editor,
      Editor,
      Toolbar
    },
    props: {
      visible: Boolean,
      id: String,
      noticetype: String,
    },
    data() {
      return {
        title: '新增/编辑通知',
        dialogVisible: false, //导入失败弹窗
        importMessage: '', //导入失败原因
        loading: false,
        activeName: 'first',
        AgreeLoading: false, //按钮loading
        labelWidth: '100px',
        ruleForm: {
          title: null, //标题
          details: null, //副标题
          content: '', //内容
          equityInventoryId: null, //权益id
          useEquity: 0, //附赠权益
          customerList: [],
          equityType: '1', //1.权益库存  2.统一链接
          unifyUrl: '', //统一链接
        },
        equityInventoryList: [], //权益列表
        whiteListLoading: false,
        addLoading: false,
        fileList: [],
        fileaction: process.env.VUE_APP_BASE_API + "/customer/message/customer/import",
        headers: {
          "X-Access-Token": getToken(),
        },
        // 表单参数
        //用户手机号
        customerformPhone: '',
        // 富文本配置
        logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/upload", //图片接口
        editor: null,
        toolbarConfig: {
          // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
          // excludeKeys: [ /* 隐藏哪些菜单 */ ],
          excludeKeys: ['group-video']
        },
        editorConfig: {
          placeholder: "请输入内容...",
          // autoFocus: false,
          // 所有的菜单配置，都要在 MENU_CONF 属性下
          MENU_CONF: {},
        },
        mode: 'default', // or 'simple'
        lookStatus: false //是否是查看
      };
    },
    computed: {},
    created() {
      this.getEquityInventoryList() // 获取权益列表
      if (this.noticetype == 'edti') {
        this.lookStatus = false
        this.title = '新增/编辑通知'
      } else if (this.noticetype == 'look') {
        this.lookStatus = true
        this.title = '查看通知'
      } else {
        this.lookStatus = false
        this.title = '新增/编辑通知'
      }
      // console.log(id)
      if (this.id != null) {
        this.getInfo()
      }
    },
    mounted() {
      var _this = this
      // 配置上传图片
      var name = ''
      this.editorConfig.MENU_CONF['uploadImage'] = {
        server: _this.logoUploadUrlImg,
        // headers: _this.headers,
        fieldName: 'file',
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        onSuccess(file, res) {
          name = file.name
          // console.log(`${file.name} 上传成功`, res)
        },
        customInsert(res, insertFn) {
          console.log(res)
          insertFn(res.result.url, name, res.result.url)
        }
      }

    },
    methods: {
      changeEquityType(e){
        console.log(e)
        if(e == 1){
          this.ruleForm.unifyUrl = ''
        }else if(e == 2){
          this.ruleForm.equityInventoryId = ''
        }
      },
      onCreated(editor) {
        this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
        if (this.lookStatus) {
          this.editor.disable() //禁用编辑
        }
      },
      onChange(editor) {
        console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
      },
      getEditorText() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getText()); // 执行 editor API
      },
      printEditorHtml() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getHtml()); // 执行 editor API
      },
      //取消
      handleClose() {
        this.$emit("update:visible", false);
      },
      /**
       * 只能输入大于0的正整数（不能以0开头）
       * @param {string} value
       * @returns {string | number} 返回空字符或数字
       */
      integerFn(value) {
        let reg = /[1-9]{1}[0-9]*$/;
        let strArray = value.split("");
        let newStrs = "";
        for (let i = 0; i < strArray.length; i++) {
          if (reg.test(strArray[i])) {
            newStrs += strArray[i];
          } else if (i > 0 && strArray[i] === "0") {
            newStrs += strArray[i];
          }
        }
        if (newStrs - 0 > 0) {
          return newStrs - 0;
        } else {
          return "";
        }
      },
      // 获取权益列表
      getEquityInventoryList() {
        let data = {
          type:''
        }
        currentInventorySelect(data).then(response => {
          this.equityInventoryList = response.result
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      // customerImport(res) {
      //     this.loading = true
      //     customerImport(file).then(response => {
      //       this.$message.success('导入成功');
      //       this.ruleForm.customerList = response.result
      //       this.loading = false
      //     }).catch(() => {
      //       this.loading = false
      //     })
      // },
      //导入文件
      handleFileChange(res, file) {
        console.log('文件', res, file)
        if (res.code == 200) {
          this.$message.success('导入成功');
          this.ruleForm.customerList = this.ruleForm.customerList.concat(res.result)
          // this.customerImport(res)
        } else {
          // this.$message.error(res.message);
          this.importMessage = res.message
          this.dialogVisible = true
          setTimeout(() => {
            this.fileList = []
          }, 800)
        }
      },
      // 上传失败
      handleFileError(res, file) {
        this.$message.error(res.message);
      },
      /** 添加按钮 */
      addUser() {
        if (this.customerformPhone == '') {
          this.$message.error('请填写手机号码');
          return
        }
        this.addLoading = true
        getCustomerPhone(this.customerformPhone).then(response => {
          this.$message.success('添加成功');
          this.ruleForm.customerList.unshift(response.result)
          this.customerformPhone = ''
          this.addLoading = false
        }).catch(() => {
          this.addLoading = false
        });
      },
      // 清空导入用户数据
      wipeData() {
        this.$confirm('是否清空通知用户表格数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.ruleForm.customerList = []

        }).catch(() => {});
      },
      /** 删除提交按钮deleteWhite */
      deleteView(index) {
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ruleForm.customerList.splice(index, 1)
        }).catch(() => {});
      },
      getInfo() { //获取信息详情
        this.loading = true
        getMessageId(this.id).then((res) => {
            this.loading = false
            let info = res.result
            this.ruleForm.title = info.title
            this.ruleForm.details = info.details
            this.ruleForm.content = info.content
            this.ruleForm.equityInventoryId = info.equityInventoryId
            this.ruleForm.useEquity = String(info.useEquity)
            this.ruleForm.customerList = info.customerList
            this.ruleForm.equityType = info.equityType
            this.ruleForm.unifyUrl = info.unifyUrl
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 判断通知内容是否为空
      checkVal(str) {
        let num = 0,
          reg = /<p>(&nbsp;|&nbsp;\s+)+<\/p>|<p>(<br>)+<\/p>/g;
        while (num < str.length && str != "") {
          num++;
          let k = str.match(reg);
          if (k) {
            str = str.replace(k[0], "");
          }
        }
        return str == "";
      },
      submitForm(status) {
        //通知状态 1草稿 2已通知
        console.log(this.ruleForm)
        if (this.ruleForm.title == null || this.ruleForm.title == '') {
          this.$message.error('请填写通知标题');
          return
        } else if (this.ruleForm.details == null || this.ruleForm.details == '') {
          this.$message.error('请填写通知副标题');
          return
        } else if (this.ruleForm.useEquity == 1 && (this.ruleForm.equityInventoryId == null||this.ruleForm.equityInventoryId == '') && this.ruleForm
          .equityType == '1') {
          this.$message.error('请选择权益');
          return
        } else if (this.ruleForm.useEquity == 1 && this.ruleForm.unifyUrl == '' && this.ruleForm.equityType == '2') {
          this.$message.error('请输入统一链接');
          return
        }

        if (status == 2) {
          if (this.checkVal(this.ruleForm.content)) {
            this.$message.error('请填写通知内容');
            return
          } else if (this.ruleForm.customerList.length == 0) {
            this.$message.error('请添加/导入通知人数');
            return
          } else if (this.ruleForm.useEquity == 1 && (this.ruleForm.equityInventoryId == null||this.ruleForm.equityInventoryId == '') && this.ruleForm
            .equityType == '1') {
            this.$message.error('请选择权益');
            return
          } else if (this.ruleForm.useEquity == 1 && this.ruleForm.unifyUrl == '' && this.ruleForm.equityType == '2') {
            this.$message.error('请输入统一链接');
            return
          }
          //效验获赠权益数量是否为空
          // var customer = false
          // var customerIndex = 0
          // this.ruleForm.customerList.some((item,index) => {
          //     if(item.codeTotal == ''){
          //       customer = true
          //       customerIndex = index+1
          //       return true
          //     }
          //   });
          // if(customer){
          //   this.$message.error('序号'+customerIndex+'获赠权益数量不能为空');
          //   return
          // }
          // if(this.noticetype == 'add'){
          //   this.addForm(status)
          // }else if(this.noticetype == 'edit'){
          //   this.editForm(status)
          // }
        }

        if (this.noticetype == 'add') {
          this.addForm(status)
        } else if (this.noticetype == 'edit') {
          this.editForm(status)
        }
      },
      addForm(status) {
        this.AgreeLoading = true
        var params = {
          ...this.ruleForm,
          status: status
        };
        addCustomerMessage(params).then((res) => {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            setTimeout(() => {
              this.$emit('success')
              this.handleClose()
              this.AgreeLoading = false
            }, 1000);
          })
          .finally(() => {
            this.AgreeLoading = false;
          });
      },
      editForm(status) {
        this.AgreeLoading = true
        var params = {
          id: this.id,
          ...this.ruleForm,
          status: status
        };
        editCustomerMessage(params).then((res) => {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            setTimeout(() => {
              this.$emit('success')
              this.AgreeLoading = false
              this.handleClose()
            }, 1000);
          })
          .finally(() => {
            this.AgreeLoading = false;
          });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  .main {
    padding: 20px 20px;
  }

  .from_box {
    display: flex;
    margin-bottom: 20px;
  }

  .tabel_box {
    margin-bottom: 20px;
  }

  .from_box_l {
    width: 110px;
    color: #606266;
    font-size: 14px;
    font-weight: bold;
  }

  .from_box_r {
    color: #333;
    font-size: 15px;
    flex: 1;
  }

  .el_table_box {
    padding: 0 20px 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .el_table_box_h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f3f3;
    margin-bottom: 14px;
  }

  .el_table_box_h_title {
    border-left: 4px solid #ff9300;
    padding-left: 4px;
  }

  .carousel_box {
    width: 400px;
    margin-bottom: 20px;
  }

  .swiper_img {
    width: 100%;
    height: 100%;
  }

  .carousel_box_two {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .phone_box {
    width: 100px;
    height: 100px;
    margin: 0 10px 10px 0;
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 228px;
    height: 128px;
    text-align: center;
    line-height: 128px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 228px;
    height: 128px;
  }

  .icon_yes {
    font-size: 30px;
    color: #67c23a;
  }

  .icon_no {
    font-size: 30px;
    color: red;
  }

  .richText {
    border: 1px solid #ccc;
    line-height: normal;
  }

</style>
